using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace MvcToolbox
{
    /// <summary>
    /// Class ModelMapperManager
    /// </summary>
    public class ModelMapperManager
    {
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public static void Initialize(Assembly _assembly = null)
        {
            Assembly assembly = _assembly;
            if (assembly == null)
            {
                assembly = System.Web.Compilation.BuildManager.GetGlobalAsaxType().BaseType.Assembly;
            }

            if (assembly != null)
            {
                var _types = assembly.GetTypes().Where(p => p.GetCustomAttributes(typeof(MapDtoAttribute), true).Count() > 0).ToList();
                foreach (var type in _types)
                {
                    MethodInfo methodInfo = type.GetMethod("Map", System.Reflection.BindingFlags.Static | BindingFlags.NonPublic);
                    if (methodInfo == null)
                    {
                        var dtoType = (type.GetCustomAttributes(typeof(MapDtoAttribute), true)[0] as MapDtoAttribute).DtoType;
                        AutoMapper.Mapper.CreateMap(dtoType, type);
                        AutoMapper.Mapper.CreateMap(type, dtoType);
                    }
                    else
                    {
                        methodInfo.Invoke(null, new object[] { });
                    }
                }
            }
        }
    }
}
